package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.CcLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Notice;
import com.example.springboot.entity.User;
import com.example.springboot.service.NoticeService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/notice")
public class NoticeController {
//    private static final Logger logger = LoggerFactory.getLogger(NoticeController.class);

    @Autowired//从spring容器中拿出来
    NoticeService noticeService;
    @Autowired
    UserService userService;

    @PostMapping("/add")
    @CcLogs(operation = "系统公告",type = LogType.ADD)
    public Result add(@RequestBody Notice notice) {
        User currentUser = TokenUtils.getCurrentUser();//获取到当前登录的用户信息
//        logger.info("开始添加通知，用户ID: {}", currentUser.getId());
        notice.setUserid(currentUser.getId());
        notice.setTime(DateUtil.now());
        try {
            noticeService.save(notice);
           //logger.info("通知添加成功，通知ID: {}", notice.getId()); // 假设Notice对象有一个getId()方法
        }
        catch (Exception e) {
//            logger.error("添加通知时发生错误", e);
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    //    修改信息
    @PutMapping("/update")
    @CcLogs(operation = "系统公告",type = LogType.UPDATE)
    public Result update(@RequestBody Notice notice) {
        noticeService.updateById(notice);
        return Result.success();
    }

    //    删除信息
    @CcLogs(operation = "系统公告",type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        noticeService.removeById(id);
        return Result.success();
    }

    //    批量删除
    @DeleteMapping("/delete/double")
    @CcLogs(operation = "系统公告",type = LogType.DOUBLEDELETE)
    public Result doubleDelete(@RequestBody List<Integer> ids) {
        noticeService.removeBatchByIds(ids);
        return Result.success();
    }

    //    查询全部
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Notice> noticeList = noticeService.list(new QueryWrapper<Notice>().orderByDesc("id"));//select * from notice order by id desc
        return Result.success(noticeList);
    }

    //    查询用户公告
    @GetMapping("/selectNotice")
    public Result selectNotice() {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>().orderByDesc("id");
        queryWrapper.eq("open",1);//用户只能看到open属性为1的
        List<Notice> noticeList = noticeService.list(queryWrapper);
        return Result.success(noticeList);
    }

    //    id查询
    @GetMapping("/selectById/{id}")
    public Result selectId(@PathVariable Integer id) {
        Notice notice = noticeService.getById(id);
        User user = userService.getById(notice.getUserid());
        if (user != null) {
            notice.setUser(user.getName());
        }
        return Result.success(notice);
    }

    //    分页多条件模糊查询
    //    pageNum当前页码
    //    一页多少个
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam String title,
                               @RequestParam Integer pageNum,
                               @RequestParam Integer pageSize) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        Page<Notice> page = noticeService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Notice> records = page.getRecords();
        for (Notice record : records) {
            Integer authorid = record.getUserid();
            User user = userService.getById(authorid);
            if (user != null) {
                record.setUser(user.getName());
            }
        }
        return Result.success(page);
    }
}

